<?
##########################################################################
#		DOCUMENTATION
##########################################################################
# A simple lib with the functions used in multiple parts of the code
#
# © LiberLab group, 2011
##########################################################################

function cleanLink($link){
	# takes a link in and replace every "/step1/step2/../"
	# with "/step1/"
	$link = preg_replace("/\/\//", "/", $link);

	$nIter = 0;
	# keep fixing until the job has been done
	$regex = "/[^\/\.]+?\/\.\./";
	preg_match($regex, $link, $results);
	while($results and $nIter < 30){
		$link = preg_replace("/(^|\/)[^\/\.]+?\/\.\.(?:\/|$)/", "$1", $link);
		$nIter++;
		preg_match($regex, $link, $results);
	}
	return $link;	
}

function getParam($param, $default = ""){
	# get a param sent using POST or GET, if default given use that if the param wasn't sent
	if (array_key_exists($param, $_REQUEST) and $_REQUEST[$param] != ""){
		$param = trim($_REQUEST[$param]);
	}else{
		$param = $default;
	}
	return $param;
}

function fromCurrentDir($link){
	# take a local directory and return a full path directory (cleaned)
	# get the current directory
	$currentDirectory = getcwd();
	# clean the directory created from the local dir given
	$directoryCleaned = cleanLink($currentDirectory . "/" . $link); 
	return $directoryCleaned;
}

final class cantOpen extends Exception{};

function mytimestamp($timeStart = null){
	# it's a wrapper function. In this way if you want to change the method used
	# for the timestamp you have to do it only in one point of the code.
	
	# if timeStart is given, returns the difference between now and that time
	$time = microtime(true);
	if ($timeStart){
		$timeEnd = $time;
		$time = $timeEnd - $timeStart;
	}
	return $time;
}

?>
